# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 2018-08-08
# Message: ngk网站的火花塞数据抓取,根据车型检索,最新版redis断点续爬,增加了html保存路径判断及自动创建,代码更加健壮
# PythonVersion: 2.7.1

import requests
import redis
import os
import sys
import hashlib
import pymysql
import json
from lxml import etree
import time

# 解决python2编码问题
reload(sys)
sys.setdefaultencoding('utf-8')

class NgkntkForCars(object):

    def __init__(self, **kwargs):
        self.db_config = kwargs.get("db_config")  # 数据库配置
        self.select_table = kwargs.get("select_table")  # 查询表名
        self.insert_table = kwargs.get("insert_table")  # 插入表名
        self.partBrand = kwargs.get("partBrand")  # 网站品牌
        self.redis_set = '{}_set'.format(kwargs.get('partBrand'))  # redis数据库集合名,用来存储查询过的pid
        self.conn1 = None  # 数据库链接和游标
        self.conn2 = None
        self.curs1 = None
        self.curs2 = None
        # self.base_path = '/Users/duanmengdi/Desktop/workspace/{}_html/'.format(kwargs.get("partBrand"))  # 存储html文件的路径
        self.base_path = os.getcwd() + '/../{}_html/'.format(self.partBrand)  # 获取当前路径并拼接出存储html文件的路径
        if not os.path.exists(self.base_path):  # 如果路径不存在,就创建一个
            os.mkdir(self.base_path)
        self.location = ""  # 重定向链接
        self.total_num = 0  # 全局计数变量
        self.sub_num = 0  # 全局备用计数变量
        self.is_sleep = kwargs.get("is_sleep", True)  # 是否控制速度的开关变量
        self.r = redis.Redis(host='localhost', port=6379, db=0).pipeline()  # redis链接,用于断点续爬
        self.make_list = kwargs.get("make_list")

        # 爬虫需要的一系列参数
        self.headers = {
            "Host": "autoparts.ngkntk.com.cn",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
            "Referer": "http://autoparts.ngkntk.com.cn/index.php?c=ngkindex",
        }

        self.cookies = {
            "_ga": "GA1.3.1972608023.1531384649",
            "PHPSESSID": "0iar3vkvjilafn2mughdfl6ph6",
            "Hm_lvt_ff7c39a62f28477ed3a9ab539595b408": "1532485013,1532917611,1533521035,1533547651",
            "Hm_lvt_92b4bca45782c0e562878a0570f97763": "1532485013,1532917611,1533521035,1533547651",
            "isClose": "yes",
            "_gid": "GA1.3.540462242.1533694870",
            "_gat": "1",
            "Hm_lpvt_92b4bca45782c0e562878a0570f97763": "1533698830",
            "Hm_lpvt_ff7c39a62f28477ed3a9ab539595b408": "1533698831",
        }

        self.brand_url = 'http://autoparts.ngkntk.com.cn/index.php?c=ngkindex&a=ngkBrandchoice'  # 获取所有车品牌的链接
        self.cars_url = 'http://autoparts.ngkntk.com.cn/index.php?c=ngkindex&a=ngkSerieschoice&brand={}'
        self.base_url = 'http://autoparts.ngkntk.com.cn'


    def get_md5(self, str):
        '''获取md5加密电子指纹'''
        md5 = hashlib.md5()
        md5.update(str)
        return md5.hexdigest()

    def get_conn(self, dbconfig_dict):
        '''获取数据库链接'''
        conn = pymysql.connect(**dbconfig_dict)
        return conn

    def get_cursor(self, conn, type='stream'):
        '''获取数据库游标'''
        if type == 'stream':
            return conn.cursor(pymysql.cursors.SSCursor)  # 返回流式游标,查询大量数据时不占用内存(返回数据形式是元组)
        elif type == 'dict':
            return conn.cursor(pymysql.cursors.DictCursor)  # 返回字典形式游标,查询出的数据以字典形式返回
        else:
            raise Exception("cursor type error")

    def construct_insert_sql(self, table, data, db=None):
        '''传入表名, 数据字典, 返回insert语句'''
        fields = '`' + '`,`'.join(data.keys()) + '`'
        values = []
        for v in data.values():
            if v == 0:
                v = '0'
            elif not v:
                v = ''
            if type(v) == int or type(v) == long:
                values.append(v.__str__())
            elif v == "now()":
                values.append(v)
            else:
                values.append("'%s'" % v.replace("'", " ").replace("\\", "\\\\"))
        if db:
            sql = 'INSERT INTO `%s`.`%s` (%s) VALUES (%s)' % (db, table, fields, ",".join(values))
        else:
            sql = 'INSERT INTO `%s` (%s) VALUES (%s)' % (table, fields, ",".join(values))
        return sql

    def parse_url(self, url, method, post_data=None, headers=None, tofile=True, **kwargs):
        requests.packages.urllib3.disable_warnings()  # 因为把ssl安全验证关了,所以不让代码报不安全的https请求警告
        pid = kwargs.get("local_pid", "")
        charset = kwargs.get("charset", "utf8")  # 暂时没有用到
        allow_redirects = kwargs.get("allow_redirects", False)  # 是否允许重定向, 默认不重定向,获取原始响应
        if method == 'GET':
            data = "GET" + url + pid  # 拼接data
            md5 = self.get_md5(data)  # 获取此次请求电子指纹
            file_path = self.base_path + md5 + ".html"
            if os.path.exists(file_path):  # 判断文件是否存在,如果存在就从本地读取
                print "GET for local"
                with open(file_path, 'r') as f:
                    res = f.read()
                response = res
            else:  # 如果路径不存在, 从web端请求
                print "GET for web"
                try:
                    response = requests.get(url=url, verify=False, headers=headers, cookies=self.cookies, timeout=30,
                                            allow_redirects=allow_redirects)
                except Exception as e:
                    response = requests.get(url=url, verify=False, headers=headers, cookies=self.cookies, timeout=30,
                                            allow_redirects=allow_redirects)

                # 每次请求都获取cookies, 并更新self.cookies(如果获取到cookies的话)
                cookies = response.cookies.get_dict()
                for k in cookies:
                    self.cookies[k] = cookies[k]

                # 获取location,
                location = response.headers.get("Location", None)
                if location:
                    print "响应头中存在location"
                    self.location = location
                    # return response.content.decode('utf8')

                if response:
                    if tofile:
                        with open(file_path, 'w') as f:  # 保存此次请求的html
                            f.write(response.content.decode('utf8'))
                    response = response.content.decode("utf8")
                else:
                    response = None

        elif method == "POST":
            data = "POST" + url + json.dumps(post_data)
            md5 = self.get_md5(data)
            file_path = self.base_path + md5 + ".html"
            if os.path.exists(file_path):  # 判断文件是否存在,如果存在就从本地读取
                print "POST for local"
                with open(file_path, 'r') as f:
                    res = f.read()
                response = res
            else:
                print "POST for web"
                try:
                    response = requests.post(url=url, data=post_data, verify=False, headers=headers,
                                             cookies=self.cookies, timeout=30,
                                             allow_redirects=allow_redirects)
                except Exception as e:
                    response = requests.post(url=url, data=post_data, verify=False, headers=headers,
                                             cookies=self.cookies, timeout=30,
                                             allow_redirects=allow_redirects)

                # 获取cookies, 并更新self.cookies
                cookies = response.cookies.get_dict()
                for k in cookies:
                    self.cookies[k] = cookies[k]

                # 获取location,
                location = response.headers.get("Location", None)
                if location:
                    print "响应头中存在location"
                    self.location = location
                    # response, file_path = self.parse_url(url=location, method="GET", headers=headers, local_pid=pid)
                    # print "已重新请求location地址"
                    # return response, file_path
                    # return response.content.decode('utf8')

                if response:
                    if tofile:
                        with open(file_path, 'w') as f:  # 保存此次请求的html
                            f.write(response.content.decode('utf8'))
                    response = response.content.decode("utf8")

                else:
                    response = None

        return response, file_path

    def r_reset(self):
        self.r.delete(self.redis_set)
        self.r.save()

    def get_cars(self):
        '''获取ngk网站所有车型,并存入数据库,作为后续获取数据依据条件'''
        self.conn1 = self.get_conn(self.db_config)
        self.curs1 = self.get_cursor(self.conn1)

        if self.is_sleep:
            time.sleep(1)

        try:
            all_brand_response, all_brand_file_path = self.parse_url(url=self.brand_url, method="GET", headers=self.headers)
        except Exception as e:
            print e
            all_brand_response, all_brand_file_path = self.parse_url(url=self.brand_url, method="GET", headers=self.headers)

        if all_brand_response:
            all_brand_html = etree.HTML(all_brand_response)
        else:
            print all_brand_file_path
            raise Exception("没有获取到所有品牌页面响应")

        all_brand_list = all_brand_html.xpath('//div[@class="n_table"]//ul/li/a')
        if len(all_brand_list) <= 0:
            print all_brand_file_path
            raise Exception("没有找到品牌列表")

        for i in all_brand_list:
            car_brand = i.xpath('./text()')
            car_brand = car_brand[0] if len(car_brand)>0 else ""

            all_car_url = self.cars_url.format(car_brand)
            try:
                all_car_response, all_car_file_path = self.parse_url(url=all_car_url, method="GET", headers=self.headers)
            except Exception as e:
                print e
                all_car_response, all_car_file_path = self.parse_url(url=all_car_url, method="GET", headers=self.headers)
            if all_car_response:
                all_car_html = etree.HTML(all_car_response)
            else:
                print all_car_file_path
                raise Exception("没有获取到车型页响应")

            all_car_list = all_car_html.xpath('//div[@class="n_brandList"]/div[@class="n_table"]/ul/li/a')
            if len(all_car_list) <= 0:
                print "没有找到车型列表, 跳过", car_brand, all_car_file_path
                continue
            for j in all_car_list:
                car = j.xpath('./text()')
                car = car[0] if len(car)>0 else ""
                car_url = j.xpath('./@href')
                car_url = self.base_url+car_url[0] if len(car_url)>0 else ""

                last_data = dict(
                    make=car_brand,
                    model=car,
                    url=car_url
                )

                sql = self.construct_insert_sql(self.select_table, last_data)
                # print sql
                # exit()
                self.curs1.execute(sql)
                self.total_num += 1

                if self.total_num % 100 == 0 :
                    print "提交insert缓存, 当前数量: {}".format(self.total_num)
                    self.conn1.commit()

        self.conn1.commit()
        print "最终提交, 总数据量: {}".format(self.total_num)

        self.curs1.close()
        self.conn1.close()

    def get_data(self, select_sql):
        self.curs1.execute(select_sql)
        for data in self.curs1:
            make=data[0]
            model=data[1]
            url=data[2]

            # 断点续爬模块
            str = make+model+url
            md5_str = self.get_md5(str)
            self.r.sismember(self.redis_set, md5_str)
            if self.r.execute()[0]:
                continue
            self.r.sadd(self.redis_set, md5_str)

            # 控制速度
            if self.is_sleep:
                time.sleep(1)

            try:
                response, file_path = self.parse_url(url=url, method="GET", headers=self.headers)
            except Exception as e:
                print e
                response, file_path = self.parse_url(url=url, method="GET", headers=self.headers)

            if response:
                html = etree.HTML(response)
            else:
                print file_path
                raise Exception("没有获取到响应, 或者产生了重定向")

            tr_list = html.xpath('//div[@class="table-c"]//tr[position()>2]')
            if len(tr_list) <= 0:
                print "没有找到需要的信息表格, 跳过", file_path
                continue

            for tr in tr_list:
                displacement = tr.xpath('./td[1]/text()')
                displacement = displacement[0] if len(displacement)>0 else ""

                years = tr.xpath('./td[2]/text()')
                years = years[0] if len(years)>0 else ""

                engine_type = tr.xpath('./td[3]/text()')
                engine_type = engine_type[0] if len(engine_type)>0 else ""

                part_num = tr.xpath('./td[4]/a/text()')
                part_num = part_num[0] if len(part_num)>0 else ""

                last_data = dict(
                    make=make,
                    model=model,
                    displacement=displacement,
                    years=years,
                    engine_type=engine_type,
                    part_num=part_num
                )

                sql = self.construct_insert_sql(self.insert_table, last_data)
                print sql

                self.curs2.execute(sql)
                self.total_num += 1
                self.r.execute()  # 提交redis缓存
                if self.total_num % 100 == 0 :
                    self.conn2.commit()
                    print "提交insert缓存, 当前数量: {}".format(self.total_num)

    def run(self):
        # 获取数据库链接
        # 获取一系列数据库链接,游标
        self.conn1 = self.get_conn(dbconfig_dict=self.db_config)
        self.conn2 = self.get_conn(dbconfig_dict=self.db_config)
        self.curs1 = self.get_cursor(conn=self.conn1)
        self.curs2 = self.get_cursor(conn=self.conn2)

        if self.make_list:
            for make in self.make_list:
                select_sql = '''select make,model,url from {} where make="{}"'''.format(self.select_table, make)
                self.get_data(select_sql)
        else:
            select_sql = '''select make,model,url from {}'''.format(self.select_table)
            self.get_data(select_sql)

        self.conn2.commit()
        print "最终提交, 总数据量: {}".format(self.total_num)

        self.curs1.close()
        self.curs2.close()
        self.conn1.close()
        self.conn2.close()


if __name__ == '__main__':
    db_config = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="my_data",
        charset="utf8"
    )
    partBrand = 'ngkntk'  # 网站品牌
    is_sleep = True  # 控制速度开关
    select_table = 'ngkntk_cars_info'  # 查询表
    insert_table = 'ngkntk_all'  # 插入表
    make_list = []  # 要获取数据的车型列表,需从数据库中获取, 如列表为空则读取所有
    tools = NgkntkForCars(db_config=db_config, partBrand=partBrand, is_sleep=is_sleep, select_table=select_table,
                         insert_table=insert_table, make_list=make_list)
    # tools.get_cars()  # 获取网站所有车型数据,并存入数据库,作为后续查询的条件
    # tools.r_reset()  # 重置断点续爬数据, 及时关闭
    tools.run()  # 启动















